package com.newlink.building.common_base.ext

import android.util.Log
import com.newlink.building.common_base.R
import com.newlink.building.common_base.base.BaseApplication
import com.newlink.building.common_base.base.IModel
import com.newlink.building.common_base.base.IView
import com.newlink.building.common_base.http.exception.Base_ExceptionHandle
import com.newlink.building.common_base.model.bean.Base_BaseBean
import com.newlink.building.common_base.utils.NetWorkUtil
import com.newlink.building.http.function.Base_RetryWithDelay
import com.newlink.building.rx.Base_SchedulerUtils
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.disposables.Disposable

/**
 * Created by xiaodong on 2023/10/10.
 */
fun <T : Base_BaseBean> Observable<T>.process(
    model: IModel?,
    view: IView?,
    isShowLoading: Boolean = true,
    onSuccess: (T?) -> Unit
) {
    this.compose(Base_SchedulerUtils.ioToMain())
        .retryWhen(Base_RetryWithDelay())
        .subscribe(object : Observer<T> {
            override fun onComplete() {
                view?.hideLoading()
            }

            override fun onSubscribe(d: Disposable) {
                if (isShowLoading) view?.showLoading()
                model?.addDisposable(d)
                if (!NetWorkUtil.isNetworkConnected(BaseApplication.instance)) {
                    view?.showDefaultMsg(BaseApplication.instance.resources.getString(R.string.network_unavailable_tip))
                    onComplete()
                }
            }

            override fun onNext(t: T) {
                Log.e("fvl_dbg", "kcp 服务器返回Code  -> ${t.code}")
                Log.e("fvl_dbg", "kcp 服务器返回msg  -> ${t.msg}")
                Log.e("fvl_dbg", "kcp 服务器返回Data  -> ${t.toString()}")
                //目前热点服务字段不全,默认每次请求成功,暂不处理相关code
                onSuccess.invoke(t)
//                when (t.code) {
//                    ErrorStatus.SUCCESS -> onSuccess.invoke(t)
//                    ErrorStatus.TOKEN_INVALID -> {
//                        // Token 过期，重新登录
//                        view?.showDefaultMsg(t.msg)
//                        Log.e("fvl_dbg" , "Token 已过期")
//                        //退出登录,清空任务栈
////                        ARouter.getInstance().build(RouterPath.PATH_LOGIN)
////                            .withAction("token_timeout")
////                            .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
////                            .navigation()
//                        EventBus.getDefault().post(ForcedExitEvent(true))
//
//                    }
//                    else -> view?.showDefaultMsg(t.msg)
//                }
            }

            override fun onError(t: Throwable) {
                view?.hideLoading()
                Log.e("fvl_dbg", "fvl_dbg: onError0 $t ")
                view?.showError(Base_ExceptionHandle.handleException(t))
            }
        })
}